const app = getApp()

Page({
  data: {
    imgUrls:'',
    indicatorDots: true,
    autoplay: true,
    duration: 1000,
    cid:'',
    classtab:[],  
    classftab:[],
    res:[],
    loadingTxt: '加载中',
    noMoreData: false,
    page: 1,
    showGoTop: false,
    size: 16
  },

  qvalue: function (e) {
    let q = e.detail.value;
    wx.navigateTo({
      url: '../listing/listing?q='+q
    })
  },

  findSubmit:function(e){
    let q = e.detail.value.q;
    wx.navigateTo({
      url: '../listing/listing?q='+q
    })
  },
 
  productCid(e) {
    let cid = e.target.dataset.id;
    this.setData({
      cid: cid,
      page: 1
    })
    this.getPorducts();
  },

  addCart:function(e){
    let id = e.target.id;
    let img_url = e.target.dataset.img;
    let price = e.target.dataset.price;
    let old_price = e.target.dataset.oldprice;
    let name = e.target.dataset.name;
    let qty = 1;
    var that = this;
    let token = wx.getStorageSync('token');
    if (token) {
      app.getUserToken(function (err, token) {
      wx.request({
        url: app.globalData.url +'/index.php?_m=checkout/cart/add_cart&v=v20190909b',
        data: { id: id, qty: qty, auth_token: token},
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },

        method: 'POST',
        success: (res) => {
          if (res.data.code == 401) {
            // 清空授权token
            app.globalData.token = null
            wx.removeStorageSync('token')
            that.addCart();
          } else if (res.data.code == 0) {
            wx.showToast({
              title: '加入购物车成功',
              icon: 'none',
              duration: 1000
            })
            setTimeout(function () {
              wx.hideToast()
            }, 1000) 
          }
        }
      })
    })
    }else{
      var cartItems = wx.getStorageSync('cartItems') || []
      var exist = cartItems.find(function (ele) {
        return ele.id === id
      })
    
    if (exist) {
      //如果存在，则增加该货品的购买数量
      exist.qty = parseInt(exist.qty) + qty
    } else {
      //如果不存在，传入该货品信息
      cartItems.push({
        id: id,
        qty: qty,
        name: name,
        img_url:img_url,
        price: price,
        old_price: old_price
      })
    }
      wx.setStorage({
        key: 'cartItems',
        data: cartItems,
        success: function (res) {
          //添加购物车的消息提示框
          wx.showToast({
            title: '加入购物车成功',
            icon: 'none',
            duration: 1000
          })
          setTimeout(function () {
            wx.hideToast()
          }, 1000)
        }
      })
    }
  },

  getPorducts() {
    var that = this;
    var page=this.data.page;
    var size=this.data.size;
    var cid = this.data.cid;

    let url = app.globalData.url+'/index.php?_m=shop/product/listing';
    if(cid !=''){
      url = app.globalData.url +'/index.php?_m=shop/product/listing&cid=' + cid;
    }
      wx.request({
        url: url,
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        method:'get',
        data: { size: size, page: page},
        success: (res) => {

          if (res.data.code == 0){
            let goods = [];
            if(page == 1){
              goods = res.data.data;
            }else{
              goods = that.data.res.concat(res.data.data);
            }
           
            that.setData({
              noMoreData: false,
              res: goods
            });

            if (res.data.data.length < that.data.size) {

              that.setData({

                loadingTxt: '没有更多内容',

                noMoreData: true,

              });

            }
          }
        }
      })
  },

  onPageScroll: function (e) {
    if (e.scrollTop > 200) {
      this.setData({
        showGoTop: true
      })
    } else {
      this.setData({
        showGoTop: false
      })
    }
  },
  // 回到顶部
  goTop: function (e) {
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },

  getCategory: function (e) {
    var that = this;
      wx.request({
        url: app.globalData.url +'/index.php?_m=shop/category/listing',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        method: 'post',
        data: {},
        success: (res) => {
          that.setData({
            classtab: res.data.data
          })
        }
      })

  },

  getBanner: function (e) {
    var that = this;
      wx.request({
        url: app.globalData.url +'/index.php?_m=index/wx/home',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        method: 'post',
        data: {},
        success: (res) => {   
          that.setData({
            imgUrls:res.data.banners,
            classftab: res.data.menus
          })
        }
      })
  },

  onLoad: function (options) {
    this.getPorducts();
    this.getCategory();
    this.getBanner();
  },

  onPullDownRefresh: function () {
    wx.showToast({
      title: '加载中...',
      icon: 'loading'
    })

    // 初始化信息
    this.getPorducts();

    setTimeout(function () {
      wx.stopPullDownRefresh()
    }, 1000)

  },

  onReachBottom: function () {
    if (!this.data.noMoreData) {  

      this.data.page = this.data.page + 1;

      this.getPorducts(true);

    };

  },
  onShareAppMessage: function () {
    app.globalData.uid = app.globalData.uid || wx.getStorageSync('uid') || 0;
    return {
      title: '深圳智汇创想科技有限责任公司员工福利购!',
      path: '/pages/index/index?fid=' + app.globalData.uid
    }
  }

})
